﻿using System;
using System.Threading;
using System.Windows.Forms;

namespace FWF.Logging.Viewer
{
    static class Program
    {
        public static frmMain MainWindow;
        public static string FilePath;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault( false );

            // Unhandled exceptions will be delivered to our ThreadException handler
            Application.ThreadException += AppThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;

            // Name the app thread
            if ( string.IsNullOrEmpty( Thread.CurrentThread.Name ) )
            {
                Thread.CurrentThread.Name = "Main Application Thread";
            }

            // TMP: ...
            FilePath = string.Empty;

            using ( MainWindow = new frmMain() )
            {
                Application.Run( MainWindow );
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void AppThreadException( object sender, ThreadExceptionEventArgs e )
        {
            var exceptionForm = new frmException();
            exceptionForm.Message = "The application has encountered an internal error.";
            exceptionForm.Exception = e.Exception;

            if ( exceptionForm.InvokeRequired )
            {
                exceptionForm.Invoke( new MethodInvoker( exceptionForm.Show ) );
            }
            else
            {
                exceptionForm.ShowDialog();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="T:System.UnhandledExceptionEventArgs"/> instance containing the event data.</param>
        private static void CurrentDomainUnhandledException( object sender, UnhandledExceptionEventArgs e )
        {
            var exceptionForm = new frmException();
            exceptionForm.Message = "The application has encountered an internal error.";
            exceptionForm.Exception = e.ExceptionObject as Exception;

            if ( exceptionForm.InvokeRequired )
            {
                exceptionForm.Invoke( new MethodInvoker( exceptionForm.Show ) );
            }
            else
            {
                exceptionForm.ShowDialog();
            }
        }

    }
}
